<?php
require_once dirname(__FILE__) . '/../../library/aliyunVod/aliyun-php-sdk-core/Config.php';
use vod\Request\V20170321 as vod;
use kms\Request\V20160120 as kms;
use live\Request\V20161101 as live;

class AliyunVod
{
    public $regionId;
    public $accessKeyId;
    public $accessKeySecret;

    function __construct($regionId = 'cn-shanghai', $accessKeyId, $accessKeySecret)
    {
        $this->regionId = $regionId;
        $this->accessKeyId = $accessKeyId;
        $this->accessKeySecret = $accessKeySecret;
    }

    public function init_vod_client()
    {
        $profile = DefaultProfile::getProfile($this->regionId, $this->accessKeyId, $this->accessKeySecret);
        return new DefaultAcsClient($profile);
    }

    public function create_upload_video($title, $filename)
    {
        $client = $this->init_vod_client();
        $request = new vod\CreateUploadVideoRequest();
        $request->setTitle($title);
        $request->setFileName($filename);
        $response = $client->getAcsResponse($request);
        return $response;
    }

    public function refresh_upload_video($videoid)
    {
        $client = $this->init_vod_client();
        $request = new vod\RefreshUploadVideoRequest();
        $request->setVideoId($videoid);
        $response = $client->getAcsResponse($request);
        return $response;
    }

    public function getVideoPlayAuth($videoid)
    {
        $client = $this->init_vod_client();
        $request = new vod\GetVideoPlayAuthRequest();
        $request->setAcceptFormat('JSON');
        $request->setRegionId($this->regionId);
        $request->setVideoId($videoid);
        $request->setAuthInfoTimeout(7200);
        $response = $client->getAcsResponse($request);
        return $response;
    }

    function getPlayAuth($videoId)
    {
        $client = $this->init_vod_client();
        $request = new vod\GetVideoPlayAuthRequest();
        $request->setVideoId($videoId);
        $request->setAuthInfoTimeout(3600);
        $request->setAcceptFormat('JSON');
        $response = $client->getAcsResponse($request);
        return $response;
    }

    public function delete_videos($videoIds)
    {
        $client = $this->init_vod_client();
        $request = new vod\DeleteVideoRequest();
        $request->setVideoIds($videoIds);
        $request->setAcceptFormat('JSON');

        return $client->getAcsResponse($request);
    }

    public function get_video_info($videoId)
    {
        $client = $this->init_vod_client();
        $request = new vod\GetVideoInfoRequest();
        $request->setVideoId($videoId);
        $request->setAcceptFormat('JSON');
        return $client->getAcsResponse($request);
    }

    public function getPlayInfo($videoId)
    {
        $client = $this->init_vod_client();
        $request = new vod\GetPlayInfoRequest();
        $request->setVideoId($videoId);
        $request->setAuthTimeout(3600 * 24);
        $request->setAcceptFormat('JSON');
        return $client->getAcsResponse($request);
    }

    /**
     * 查询转码模板组列表！！！！有问题
     */
    public function templategrouplist()
    {
        $client = $this->init_vod_client();
        $request = new vod\ListTranscodeTemplateGroupRequest();
        return $client->getAcsResponse($request);
    }

    /**
     *获取转码组模板的详细信息 ！！！！有问题
     */
    public function gettemplateinfo()
    {
        $client = $this->init_vod_client();
        $request = new vod\GetTranscodeTemplateGroupRequest();
        // 转码模板组ID
        $request->setTranscodeTemplateGroupId('76eff5bc54a891fbf33ec1263f5357df');
        return $client->getAcsResponse($request);
    }


    /**
     * 构建覆盖参数，目前只支持图片水印文件地址、文字水印的内容覆盖；如不使用可忽略
     * 需要替换的水印信息对应水印ID必须是关联在指定的转码模板组ID上(即TranscodeTemplateId)
     * 不支持通过媒体处理接口去增加一个没有关联上的水印
     */
    /*function buildOverrideParams() {
        $overrideParams = array();
        //以替换水印为例
        $watermarks = array();
        //替换图片水印文件
        $watermarks1 = array();
        $watermarks1["WatermarkId"] = "2ea587477c5a1bc8bxxxxx";
        $watermarks1["FileUrl"] = "https://outin-40564284ef05113e1403e7.oss-cn-shanghai.aliyuncs.com/watermarks/02A1B22DF25D46C3C725A4-6-2.png";
        $watermarks[] = $watermarks1;
        //替换文字水印
        $watermarks2 = array();
        $watermarks2["WatermarkId"] = "d297ba31ac5242d20xxxxx";
        $watermarks2["Content"] = "用户ID：66666";
        $watermarks[] = $watermarks2;
        $overrideParams["Watermarks"] = $watermarks;
        return json_encode($overrideParams);
    }*/
    /**
     * 生成HLS标准加密参数的可选配置，如不使用可忽略
     * 此时依赖KMS服务，需要安装KMS依赖包 aliyun-php-sdk-kms
     * 生成密钥API参考：https://help.aliyun.com/document_detail/28948.html
     */
    public function buildEncryptConfig()
    {
        $client = $this->init_vod_client();
        try {
            //随机生成一个加密的秘钥，返回的response包含明文秘钥以及密文秘钥，
            //视频标准加密只需要传递密文秘钥即可
            echo 12456;
            $request = new kms\GenerateDataKeyRequest();
            print_r($request);
            $request->setKeyId($this->accessKeySecret);
            $request->setKeySpec("AES_128");
            $response = $client->getAcsResponse($request);
            $encryptConfig = array();
            # 解密接口地址，该参数需要将每次生成的密文秘钥与接口URL拼接生成，表示每个视频的解密的密文秘钥都不一样；注意您需要自己部署解密服务
            $encryptConfig["DecryptKeyUri"] = "http://decrypt.demo.com/decrypt?Ciphertext=" . $response->getCiphertextBlob();
            //秘钥服务的类型，目前只支持KMS
            $encryptConfig["KeyServiceType"] = "KMS";
            /*# Ciphertext作为解密接口的参数名称，可自定义，此处只作为参考
            $encryptConfig["CipherText"] = $response->getCiphertextBlob();*/
            //var_dump($encryptConfig);
            return json_encode($encryptConfig);
        } catch (Exception $e) {
            var_dump($e->getMessage());
        }
    }

    /**
     * 提交媒体处理作业
     */
    public function submitTranscodeJobs($vid, $templeteid)
    {
        $client = $this->init_vod_client();
        $request = new vod\SubmitTranscodeJobsRequest();
        //需要转码的视频ID
        $request->setVideoId($vid);
        //转码模板ID
        $request->setTemplateGroupId($templeteid);


        /*//构建需要替换的水印参数(只有需要替换水印相关信息才需要构建)
        $request->setOverrideParams(buildOverrideParams());*/
        //HLS标准加密配置(只有标准加密才需要传递)
        $aa = $this->buildEncryptConfig();

        $request->setEncryptConfig($aa);

        return $client->getAcsResponse($request);
    }



    /**
     *获取推流地址参数
     * DescribeLiveStreamsBlockList  获取域名下直播流播放的黑名单。
     * DescribeLiveStreamsControlHistory   获取某个域名或应用下的直播流操作记录
     * DescribeLiveStreamBitRateData  询RTMP协议的直播流的设置时间范围内的一组帧率和码率，适用于获取历史数据
     * DescribeLiveStreamsOnlineList  查看指定域名下（或者指定域名下某个应用）的所有正在推的流的信息。
     * DescribeLiveStreamsPublishList  获取某一时间段内某个域名（或域名下某应用或某个流）的推流记录。
     * ForbidLiveStream  禁止某条流的推送，可以预设某个时刻将流恢复。
     * ResumeLiveStream 恢复某条流的推送。
     * DescribeLiveDomainFrameRateAndBitRateData  查询直播域名下流帧率和码率数据。
     * DescribeLiveDomainOnlineUserNum 查询域名下所有流某分钟的在线人数信息
     *AddLiveRecordVodConfig  调用AddLiveRecordVodConfig增加直播录制转点播配置，将录制内容保存到点播媒资库
     */
    /**
     * 获取正在直播的推流信息列表
     * @param $yuming
     * @return mixed|string
     */
    public function getonlinelist($yuming)
    {
        $client = $this->init_vod_client();
        $request = new live\DescribeLiveStreamsOnlineListRequest();
        $request->setDomainName($yuming);
        $result = $client->getAcsResponse($request);
        return json_encode($result);
    }

    /**
     * 获取直播域名的配置信息
     * @param $yuming
     * @return mixed|string
     */
    public function getLivedomaindetail($yuming)
    {
        $client = $this->init_vod_client();
        $request = new live\DescribeLiveDomainDetailRequest();
        $request->setDomainName($yuming);
        $result = $client->getAcsResponse($request);
        return json_encode($result);
    }

    public function getlivedomainconfigs($yuming, $functions)
    {
        $client = $this->init_vod_client();
        $request = new live\DescribeLiveDomainConfigsRequest();
        $request->setFunctionNames($functions);
        $request->setDomainName($yuming);
        $result = $client->getAcsResponse($request);
        return json_encode($result);
    }

    /**
     * 摸个域名下的推流记录  就是这个推流开启了多少次就会有多少个记录
     * @param $yuming 域名
     * @param $starttime 开始时间  2019-09-18T08:00:00Z
     * @param $endtime 结束时间  格式同上
     * @return mixed|string
     */
    public function getpushinfo($yuming, $starttime, $endtime)
    {
        $client = $this->init_vod_client();
        $request = new live\DescribeLiveStreamsPublishListRequest();
        $request->setDomainName($yuming);
        $request->setStartTime($starttime);
        $request->setEndTime($endtime);
        $result = $client->getAcsResponse($request);
        return json_encode($result);
    }

    /**
     * 增加直播转点播配置
     * @param $yuming  加速域名
     * @param $appname
     * @param $vodtranscodegroupid  点播转码组模板id
     * @param int $time 周期时长 默认1个小时  单位秒
     * @return mixed|string
     */
    public function addliverecordvodconfig($yuming, $appname, $vodtranscodegroupid, $time = 3600)
    {
        $client = $this->init_vod_client();
        $request = new live\AddLiveRecordVodConfigRequest();
        $request->setDomainName($yuming);
        $request->setAppName($appname);
        $request->setVodTranscodeGroupId($vodtranscodegroupid);
        $request->setCycleDuration($time);
        $result = $client->getAcsResponse($request);
        return json_encode($result);
    }

}


